package Dictionary;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 * This is the Full Dictionary UI. In this user can enter a word and view the meaning.
 * The language is automatically detected.
 * @author SUMEDHA
 */
public class DictionaryUI extends javax.swing.JFrame {

    private HashMap<String, String> engToSin;
    private HashMap<String, String> sinToEng;
    private String englishWord, sinhalaWord;

    /**
     * Creates new form DictionaryUI
     * @param dbr  A DataBaseReader Object
     */
    public DictionaryUI(DataBaseReader dbr) {
        try {
            //HashMaps containing the dictionary data
            this.engToSin = dbr.getEngToSin();
            this.sinToEng = dbr.getSinToEng();
            //Setting the System Look and Feel
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());    
            initComponents();
            //Setting the location of the frame
            this.setLocationRelativeTo(null);
            //Starting Key Listeners
            startKeyListening();
            //Set tooltips for the text fields
            enterWordTextField.setToolTipText("Enter the word");
            displayTextArea.setToolTipText("Meaning");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DictionaryUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(DictionaryUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(DictionaryUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(DictionaryUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        enterWordTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        displayTextArea = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        viewButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Dictionary");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(196, 202, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        enterWordTextField.setFont(new java.awt.Font("Iskoola Pota", 0, 18));

        displayTextArea.setFont(new java.awt.Font("Iskoola Pota", 0, 18));
        displayTextArea.setRows(5);
        jScrollPane1.setViewportView(displayTextArea);

        jLabel2.setFont(new java.awt.Font("SansSerif", 1, 14));
        jLabel2.setText("Meaning ");

        viewButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Dictionary/find.png"))); // NOI18N
        viewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewButtonActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("SansSerif", 1, 14));
        jLabel3.setText("Enter the word you want to search");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Dictionary/openoffice-logo-small.jpg"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(enterWordTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(96, 96, 96)
                        .addComponent(viewButton))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(21, 21, 21)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(enterWordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(viewButton)
                .addGap(19, 19, 19)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * The method to view the meaning.
     * It reads the word which has been entered by the user and displays the meaning.
     * The language is detected automatically
     * @param evt
     */
    private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewButtonActionPerformed

        //Getting the word enterd by the user
        String word = enterWordTextField.getText();

        //Determining the language
        int type = word.codePointAt(0);

        //For english
        if (type > 64 && type < 123) {
            word = word.toLowerCase();
            englishWord = word;
            enterWordTextField.setEnabled(true);
            enterWordTextField.selectAll();
            displaySinhalaMeaning();
        } //For sinhala
        else if (type > 3455 && type < 3553) {
            sinhalaWord = word;
            enterWordTextField.setEnabled(true);
            enterWordTextField.selectAll();
            displayEnglishMeaning();

        }

    }//GEN-LAST:event_viewButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea displayTextArea;
    private javax.swing.JTextField enterWordTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton viewButton;
    // End of variables declaration//GEN-END:variables

    /**
     * This method is used to display the Sinhala meaning of a word
     * The meaning is taken from the HashMap created(DatabaseReader Object)
     * when the extension initialize
     */
    public void displaySinhalaMeaning() {
        //Checking wheather the word is in the dictionary
        if ((engToSin.get(englishWord)) != null) {      
            String sinhalaMeaning = engToSin.get(englishWord);
            displayTextArea.setLineWrap(true);
            displayTextArea.setText(sinhalaMeaning);

        } //If the word is not in the dictionary
        else {
            JOptionPane.showMessageDialog(rootPane, "Sorry. The word is not in "
                    + "the database. Try a new Word", "Message", WIDTH, null);
            displayTextArea.setText("");
            enterWordTextField.setText("");
            enterWordTextField.setEnabled(true);
        }


    }

    /**
     * This method is used to display the English meaning of a word
     * The meaning is taken from the HashMap created(DatabaseReader Object)
     * when the extension initialize
     */
    public void displayEnglishMeaning() {
        //Checking wheather the word is in the dictionary
        if ((sinToEng.get(sinhalaWord)) != null) {      
            String englishMeaning = sinToEng.get(sinhalaWord);
            displayTextArea.setLineWrap(true);
            displayTextArea.setText(englishMeaning);

        } //If the word is not in the dictionary
        else {
            JOptionPane.showMessageDialog(rootPane, "Sorry. The word is not in "
                    + "the database. Try a new Word", "Message", WIDTH, null);
            displayTextArea.setText("");
            enterWordTextField.setText("");
            enterWordTextField.setEnabled(true);
        }


    }

    /**
     * This KeyListener Class is used to catch the enter key pressing by the user
     * after entering the word
     */
    public class KeyListener extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
                viewButton.doClick();
            }
        }
    }

    private void startKeyListening() {
        viewButton.addKeyListener(new KeyListener());
        enterWordTextField.addKeyListener(new KeyListener());
    }
}
